// wallpaper-manager.js
const fs = require('fs');
const path = require('path');
const wallpaper = require('wallpaper');
const crypto = require('crypto');

// 获取文件夹中的所有图片文件
function getImagesFromFolder(folderPath) {
  const files = fs.readdirSync(folderPath);
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.bmp', '.gif','.webp'];

  return files.filter(file => {
    const ext = path.extname(file).toLowerCase();
    return imageExtensions.includes(ext);
  }).map(file => path.join(folderPath, file));
}

// 随机选择一张壁纸
function getRandomWallpaper(folderPath) {
  const images = getImagesFromFolder(folderPath);

  if (images.length === 0) {
    throw new Error('文件夹中没有找到图片文件');
  }

  const randomIndex = crypto.randomInt(0, images.length);
  return images[randomIndex];
}

// 更换壁纸
async function changeWallpaper(folderPath) {
  try {
    const wallpaperPath = getRandomWallpaper(folderPath);
    // 检查 wallpaper 模块的正确用法
    await wallpaper.set(wallpaperPath, {
      scale: 'fit' // 使图片适应屏幕，完整显示而不裁剪
    });
    return wallpaperPath;
  } catch (err) {
    throw new Error(`更换壁纸失败: ${err.message}`);
  }
}

module.exports = {
  changeWallpaper,
  getRandomWallpaper
};